# -*- coding:utf-8 -*-
from redis_opreator import RedisOperator

__author__ = 'CYY'

import db_util
from constant_util import path

ro = RedisOperator()


def exec_from_redis():
    if ro.is_key_not_exist():
        ro.add2redis(-1)
    exec_id_list = ro.get_all2redis()
    if exec_id_list is not None:
        end_exec_id_list = []
        for i in exec_id_list:
            sql = "SELECT count(1) as exec_id  FROM `execution_flows` where exec_id=" + i + " and end_time!=-1"
            count = db_util.exec_mysql_sql(sql)[0].get('exec_id')
            if count > 0:
                ro.remove2redis(int(i))
                end_exec_id_list.append(i)

        exec_id_str = exec_id_list[0]
        for i in range(1, len(exec_id_list)):
            exec_id_str += "," + exec_id_list[i]
        sql_select = "SELECT a.*,b.name from execution_flows as a LEFT JOIN projects as b ON a.project_id=b.id where a.exec_id in(" + exec_id_str + ") and  a.status in('60','70','125')"
        result = db_util.exec_mysql_sql(sql_select)
        return list(result)



def set_to_redis(exec_id):
    sql = "SELECT exec_id from execution_flows  where exec_id >" + exec_id + " and end_time = -1"
    result = db_util.exec_mysql_sql(sql)
    if result is not None:
        for i in result:
            ro.add2redis(int(i.get('exec_id')))


def exec_from_fileid(exec_id_last):
    # with open(path, 'r') as f:
    #     exec_id_last = f.read()
    set_to_redis(exec_id_last)
    if exec_id_last is not None:
        sql = "SELECT a.*,b.name from execution_flows as a LEFT JOIN projects as b ON a.project_id=b.id where a.exec_id >" + exec_id_last + " and  a.status in('60','70','125')"
        result = db_util.exec_mysql_sql(sql)
        return list(result)


def exec_sql():
    with open(path, 'r') as f:
        exec_id_last = f.read()
    # if exec_id_last is not None:
    #     sql = "SELECT a.*,b.name from execution_flows as a LEFT JOIN projects as b ON a.project_id=b.id where a.exec_id >" + exec_id_last + " and  a.status in('60','70','125')"
    #     result = db_util.exec_mysql_sql(sql)
    result = exec_from_redis() + exec_from_fileid(exec_id_last)
    if result is not None:
        err_msg = []
        for result_detail in result:
            err_msg.append(result_detail)
        sql_next = "SELECT max(exec_id) as exec_id FROM `execution_flows` where exec_id >" + exec_id_last
        result_next = db_util.exec_mysql_sql(sql_next)
        exec_id_now = result_next[0].get('exec_id')
        if exec_id_now is not None:
            with open(path, 'w') as f:
                f.write(str(exec_id_now))
        return err_msg


if __name__ == '__main__':
    # with open(path, 'r') as f:
    #     #     exec_id_last = f.read()
    #     # result1=exec_from_redis()
    #     # result2=exec_from_fileid(exec_id_last)
    #     # pass
    print(exec_sql())
